package com.lqk.testnewflutter.flutter

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import com.google.gson.Gson
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.JSONMessageCodec
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.nio.ByteBuffer

/**
 *
 * @auther LQK 2025-07-01 23:34
 */
class TestFlutterFragment : FlutterFragment() {

    companion object {
        const val TAG = "TestFlutterFragment"

        // 普通 通道
        const val CHANNEL = "CHANNEL"

        // 事件通道
        const val CHANNEL_EVENT = "CHANNEL_EVENT"

        // 普通消息
        const val CHANNEL_BASIC_MESSAGE = "CHANNEL_BASIC_MESSAGE"

        // 信使监听
        const val CHANNEL_BINARY = "CHANNEL_BINARY"
    }

    // flutter engine 初始化的回调
    // 增加自己的回调等事件
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        initMethodChannel(flutterEngine)
        initEventChannel(flutterEngine)
        initBasicMessageChannel(flutterEngine)
        initBinaryMessenger(flutterEngine)
    }

    ///<editor-fold desc="- NativeChannel">

    var native2Flutter: MethodChannel? = null

    /**
     * 初始化
     */
    fun initMethodChannel(flutterEngine: FlutterEngine) {
        native2Flutter = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
        native2Flutter?.setMethodCallHandler { methodCall, methodChannelResult ->
            dispatchFlutterMethod(methodCall, methodChannelResult)
        }
    }

    /**
     * 接收事件并分发
     */
    fun dispatchFlutterMethod(methodCall: MethodCall, result: MethodChannel.Result) {
        Log.d(TAG, "${methodCall.method}, ${methodCall.arguments}")
        when (methodCall.method) {
            "test" -> {

            }

            "toast" -> {
                val msg = methodCall.arguments.toString()
                if (msg.isNotEmpty()) {
                    Toast.makeText(this.requireContext(), msg, Toast.LENGTH_SHORT).show()
                }
            }

            "hookBackPressed" -> {}

            else -> {
                result.notImplemented()
            }
        }
    }

    /**
     * 给 Flutter 发送消息
     */
    fun send2Flutter(methodName: String, obj: Any, result: MethodChannel.Result? = null) {
        Log.d(TAG, "send2Flutter: $methodName ${Gson().toJson(obj)}")
        native2Flutter?.invokeMethod(methodName, obj, result)
    }

    ///</editor-fold>

    ///<editor-fold desc="- EventChannel">

    var eventChannel: EventChannel? = null

    var eventSink: EventChannel.EventSink? = null

    /**
     * 初始化并设置监听
     */
    fun initEventChannel(engine: FlutterEngine) {
        eventChannel = EventChannel(engine.dartExecutor.binaryMessenger, CHANNEL_EVENT)
        eventChannel?.setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
                Log.d(TAG, "onListen: $arguments")
                stop = false
                if (eventSink == null) {
                    // 保存 event 对象
                    eventSink = events
                    // 开始发送
                    startSendEvent()
                } else {
                    // 重复开启的处理
                }
            }

            override fun onCancel(arguments: Any?) {
                Log.d(TAG, "onCancel: $arguments")
                stop = true
                eventSink?.endOfStream()
                eventSink = null
            }
        })
    }

    fun sendEvent(event: Any) {
        eventSink?.success(event)
    }

    @Volatile
    var stop = false
    val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            sendEvent(msg.what)
            if (!stop) {
                sendEmptyMessageDelayed(++msg.what, 500L)
            }
        }
    }

    fun startSendEvent() {
        handler.sendEmptyMessage(0)
    }

    ///</editor-fold>

    ///<editor-fold desc="- BasicMessageChannel">

    var basicMessageChannel: BasicMessageChannel<Any>? = null

    /**
     * 初始化
     */
    fun initBasicMessageChannel(engine: FlutterEngine) {
        basicMessageChannel = BasicMessageChannel(engine.dartExecutor.binaryMessenger, CHANNEL_BASIC_MESSAGE, JSONMessageCodec.INSTANCE);
        basicMessageChannel?.setMessageHandler { message, reply ->
            dispatchMessage(message, reply)
        }
    }

    /**
     * 数据处理
     */
    fun <T> dispatchMessage(message: T, reply: BasicMessageChannel.Reply<T>) {
        Log.d(TAG, "dispatchMessage: $message $reply")
        // 结果返回
        reply.reply(message)
    }

    /**
     * 发送消息
     */
    fun sendMessage(message: Any) {
        basicMessageChannel?.send(message, object : BasicMessageChannel.Reply<Any> {
            override fun reply(reply: Any?) {
                Log.d(TAG, "reply: $reply")
            }
        })
    }

    ///</editor-fold>

    ///<editor-fold desc="- BinaryMessenger">
    var binaryMessenger: BinaryMessenger? = null

    /**
     * 保存 binaryMessenger 对象
     */
    fun initBinaryMessenger(flutterEngine: FlutterEngine) {
        binaryMessenger = flutterEngine.dartExecutor
        listenBinaryMessenger(CHANNEL_BINARY)
    }

    /**
     * 数据监听
     */
    fun listenBinaryMessenger(channelName: String) {
        binaryMessenger?.setMessageHandler(channelName, object : BinaryMessenger.BinaryMessageHandler {
            override fun onMessage(message: ByteBuffer?, reply: BinaryMessenger.BinaryReply) {
                // 消息处理
                Log.d(TAG, "onBinaryMessage: ${message}")
            }
        })
    }

    /**
     * 发送数据
     */
    fun sendBinaryMessenger(channelName: String = CHANNEL_BINARY) {
        Log.d(TAG, "sendBinaryMessenger: ")
        val data = ByteBuffer.allocate(10);
        data.put(byteArrayOf(9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
//        binaryMessenger?.send(CHANNEL_BINARY, data)
    }
    ///</editor-fold>


    ///<editor-fold desc="- 原生功能">
    // 是否拦截系统返回
    var isHook = false

    override fun onBackPressed() {
        if (isHook) return
        super.onBackPressed()
    }
    ///</editor-fold>
}